'use strict';
const { Service } = require('egg');

class AuthorizationService extends Service {
  async getDetailFromCode(code) {
    const { ctx } = this;
    return await ctx.model.Code.findOne({ where: { code } });
  }

  async getCodeFromToken(token) {
    const { ctx } = this;
    return await ctx.model.Token.findOne({ where: { token } });
  }

  async getDetailFromToken(token) {
    const code = await this.getCodeFromToken(token);
    if (!code) return null;

    return await this.getDetailFromCode(code.code);
  }

  async getCurrentUser() {
    const { ctx } = this;
    const authorization = ctx.get('Authorization').slice(7);
    const detail = await ctx.service.authorization.getDetailFromToken(authorization);
    if (!detail) return null;
    return detail.user;
  }

  async getCurrentScope() {
    const { ctx } = this;
    const authorization = ctx.get('Authorization').slice(7);
    const detail = await ctx.service.authorization.getDetailFromToken(authorization);
    if (!detail) return null;
    return JSON.parse(detail.scope);
  }
}

module.exports = AuthorizationService;
